package indi.wshape1.takeawaydeliveryinfo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import indi.wshape1.takeawaydeliveryinfo.pojo.*;
import indi.wshape1.takeawaydeliveryinfo.pojo.response.LoginInfo;
import indi.wshape1.takeawaydeliveryinfo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author Wshape1
 * @version 1.0
 * @description 处理Post请求
 * @since 2023-01-17
 */

@RestController
public class PostController {

    @Autowired
    private SenderService senderService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RootService rootService;

    @Autowired
    private TakeoutInfoService takeoutInfoService;

    @Autowired
    private BlockService blockService;

    @Autowired
    private GroupService groupService;


    /**
     * 进行登录验证并跳转到后台
     * resp.data:
     * OK - 成功登录
     * ERROR_x:msg - 出现错误
     * x = 0 账号密码错误
     * x = 1 账号已登录
     * msg: 错误信息
     *
     * @param loginInfo
     * @param response
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestBody LoginInfo loginInfo, HttpServletRequest request, HttpServletResponse response) {
        String type = loginInfo.getType();
        String phone = loginInfo.getPhone();
        String password = loginInfo.getPassword();

        if (request.getServletContext().getAttribute(phone) != null)
            return "ERROR_1:账号已登录";

        // 分角色进行登录认证
        boolean pass = false;
        switch (type) {
            case "sender":
                pass = senderService.verify(phone, password);
                break;
            case "admin":
                pass = adminService.verify(phone, password);
                break;
            case "root":
                pass = rootService.verify(phone, password);
                break;
        }

        if (pass) {
            request.getSession().setAttribute("phone", phone);
            request.getServletContext().setAttribute(phone, type);
            if (loginInfo.isNoLogin()) {
                Cookie cookie = new Cookie("noLogin", type + ":" + phone + ":" + password);
                cookie.setMaxAge(259200);   //单位秒 时间三天
                response.addCookie(cookie);
            }
            return "OK";
        }
        return "ERROR_0: 账号密码错误";
    }

    /**
     * （批量）处理外卖信息配送状态修改
     *
     * @param ids
     * @return
     */
    @PostMapping("/page/send")
    @Transactional(timeout = 5)
    public String handleSend(@RequestBody List<Integer> ids) {
        int i = takeoutInfoService.toggleStatusBatch(ids);
        if (i <= 0)
            return "ERROR:All_Failed";
        else if (i < ids.size())
            return "ERROR:Partial_Success:" + i;
        return "OK";
    }

    /**
     * 处理删除 takeaway sender admin group block
     *
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("/page/delete")
    @Transactional(timeout = 5)
    public String handleDelete(@RequestParam("type") String type, @RequestBody List<Integer> ids) {
        boolean isSuccess = false;
        switch (type) {
            case "takeaway":
                isSuccess = takeoutInfoService.removeBatchByIds(ids);
                break;
            case "sender":
                isSuccess = senderService.removeBatchByIds(ids);
                break;
            case "admin":
                isSuccess = adminService.removeBatchByIds(ids);
                break;
            case "group":
                // 因为有外键约束 所以要先让group下的sender ‘free’

                takeoutInfoService.removeBatchByGroupIds(ids);
                senderService.freeSenderBatchByGroupIds(ids);
                isSuccess = groupService.removeBatchByIds(ids);
                break;
            case "block":
                // 同上 考虑外键约束

                takeoutInfoService.removeBatchByBlockIds(ids);
                senderService.freeSenderBatchByBlockIds(ids);
                groupService.removeBatchByBlockIds(ids);
                adminService.freeAdminBatchByBlockIds(ids);
                isSuccess = blockService.removeBatchByIds(ids);
                break;
        }
        if (isSuccess)
            return "OK";
        else
            return "ERROR:All_Failed";
    }

    /**
     * 修改名字
     *
     * @param name
     * @return
     */
    @PostMapping("/change/info")
    @Transactional(timeout = 5)
    public String handleChangeInfo(@RequestBody String name, HttpSession session) throws UnsupportedEncodingException {
        String decode = URLDecoder.decode(name, StandardCharsets.UTF_8);
        name = decode.substring(0, decode.length() - 1);
        String phone = (String) session.getAttribute("phone");
        String type = (String) session.getServletContext().getAttribute(phone);

        boolean isSuccess = false;

        switch (type) {
            case "sender":
                UpdateWrapper<Sender> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("phone", phone).set("name", name);
                isSuccess = senderService.update(updateWrapper);
                break;
            case "admin":
                UpdateWrapper<Admin> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.eq("phone", phone).set("name", name);
                isSuccess = adminService.update(updateWrapper1);
                break;
        }
        if (isSuccess)
            return "OK";
        else
            return "ERROR";
    }

    /**
     * 修改密码
     *
     * @param newPwd
     * @return
     */
    @PostMapping("/change/pwd")
    @Transactional(timeout = 5)
    public String handleChangePwd(@RequestBody String newPwd, HttpSession session) {
        newPwd = newPwd.substring(0, newPwd.length() - 1);
        boolean isSuccess = false;
        String errMsg = "ERROR";
        String phone = (String) session.getAttribute("phone");
        String type = (String) session.getServletContext().getAttribute(phone);

        switch (type) {
            case "sender":
                QueryWrapper<Sender> senderQueryWrapper = new QueryWrapper<>();
                senderQueryWrapper.eq("phone", phone);
                if (newPwd.equals(senderService.getOne(senderQueryWrapper).getPassword())) {
                    errMsg += ":OldPwd_Inconsistent";
                    break;
                }

                UpdateWrapper<Sender> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("phone", phone).set("password", newPwd);
                isSuccess = senderService.update(updateWrapper);
                break;
            case "admin":
                QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
                adminQueryWrapper.eq("phone", phone);
                if (newPwd.equals(adminService.getOne(adminQueryWrapper).getPassword())) {
                    errMsg += ":OldPwd_Inconsistent";
                    break;
                }

                UpdateWrapper<Admin> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.eq("phone", phone).set("password", newPwd);
                isSuccess = adminService.update(updateWrapper1);
                break;
            case "root":
                QueryWrapper<Root> rootQueryWrapper = new QueryWrapper<>();
                rootQueryWrapper.eq("name", phone);
                if (newPwd.equals(rootService.getOne(rootQueryWrapper).getPassword())) {
                    errMsg += ":OldPwd_Inconsistent";
                    break;
                }

                UpdateWrapper<Root> updateWrapper2 = new UpdateWrapper<>();
                updateWrapper2.eq("name", phone).set("password", newPwd);
                isSuccess = rootService.update(updateWrapper2);
                break;
        }

        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }

    /**
     * 添加外卖信息
     *
     * @param takeoutInfo
     * @param session
     * @return
     */
    @PostMapping("/more/add/takeaway")
    public String addTakeaway(@RequestBody TakeoutInfo takeoutInfo, HttpSession session) {
        String errMsg = "ERROR";
        boolean isSuccess = false;

        takeoutInfo.setTime(new Date());
        takeoutInfo.setSenderPhone((String) session.getAttribute("phone"));
        takeoutInfo.setStatus("配送中");

        isSuccess = takeoutInfoService.save(takeoutInfo);

        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }

    /**
     * 添加配送员
     *
     * @param sender
     * @return
     */
    @PostMapping("/more/add/sender")
    public String addSender(@RequestBody Sender sender) {
        String errMsg = "ERROR";
        boolean isSuccess = false;

        QueryWrapper<Sender> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", sender.getPhone());
        if (senderService.getOne(queryWrapper) == null) {

            isSuccess = senderService.save(sender);

        } else {
            errMsg += ":Exist";
        }


        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }

    /**
     * 添加管理员
     *
     * @param admin
     * @return
     */
    @PostMapping("/more/add/admin")
    public String addAdmin(@RequestBody Admin admin) {
        String errMsg = "ERROR";
        boolean isSuccess = false;

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", admin.getPhone());
        if (adminService.getOne(queryWrapper) == null) {

            isSuccess = adminService.save(admin);

        } else {
            errMsg += ":Exist";
        }

        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }

    /**
     * 添加组别
     *
     * @param group
     * @return
     */
    @PostMapping("/more/add/group")
    public String addGroup(@RequestBody Group group) {
        String errMsg = "ERROR";
        boolean isSuccess = false;

        QueryWrapper<Group> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_name", group.getGroupName());
        if (groupService.getOne(queryWrapper) == null) {

            isSuccess = groupService.save(group);

        } else {
            errMsg += ":Exist";
        }

        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }

    /**
     * 添加区块
     *
     * @param block
     * @return
     */
    @PostMapping("/more/add/block")
    public String addBlock(@RequestBody Block block) {
        String errMsg = "ERROR";
        boolean isSuccess = false;

        QueryWrapper<Block> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("block_name", block.getBlockName());
        if (blockService.getOne(queryWrapper) == null) {

            isSuccess = blockService.save(block);

        } else {
            errMsg += ":Exist";
        }

        if (isSuccess)
            return "OK";
        else
            return errMsg;
    }


}
